<template>
  <el-dialog width="80%" v-model="visible" :title="!dataForm.id ? $t('add') : $t('update')" :close-on-click-modal="true" :close-on-press-escape="true">
    <el-form :model="dataForm" :rules="rules" ref="dataFormRef" label-width="140px">
      <el-form-item label="标题" prop="title" disabled>
        <el-input v-model="dataForm.title" placeholder="名称" disabled></el-input>
      </el-form-item>
      <el-form-item label="封面" prop="uploadUrl">
        <!-- <el-upload :action="uploadUrl" ref="uploadRef" :multiple="false" list-type="picture-card" :limit="1" :before-upload="uploadBeforeUploadHandle" :on-success="uploadSuccessHandle">
          <el-icon><Plus /></el-icon>
        </el-upload> -->

        <div class="demo-image__preview">
          <el-radio-group v-model="dataForm.url">
            <div class="image-item" v-for="(item, index) in imgSrc" :key="index">
              <el-image style="width: 100px; height: 100px; margin: 3px" :src="item" :zoom-rate="1.2" :max-scale="7" :min-scale="0.2" :preview-src-list="imgSrc" :initial-index="index" fit="cover" />
              <el-radio :label="item">选择</el-radio>
            </div>
          </el-radio-group>
        </div>
      </el-form-item>
    </el-form>
    <template v-slot:footer>
      <el-button @click="visible = false">{{ $t("cancel") }}</el-button>
      <el-button type="primary" @click="dataFormSubmitHandle()" :loading="loading">{{ $t("confirm") }}</el-button>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { reactive, ref } from "vue";
import baseService from "@/service/baseService";
import { useI18n } from "vue-i18n";
import { ElMessage } from "element-plus";
import app from "@/constants/app";
import { getToken } from "@/utils/cache";
import { Plus, Delete } from "@element-plus/icons-vue";
const { t } = useI18n();
const emit = defineEmits(["refreshDataList"]);
const uploadRef: any = ref(null);

const visible = ref(false);
const loading = ref(false);
const dataFormRef = ref();
const imgSrc: any = ref([]);

const dataForm = reactive({
  id: "",
  title: "",
  content: "",
  author: "",
  url: "",
  type: 1,
  status: 1
});

const rules = ref({
  title: [{ required: true, message: t("validate.required"), trigger: "blur" }],
  content: [{ required: true, message: t("validate.required"), trigger: "blur" }]
});

const init = (id?: number) => {
  visible.value = true;
  dataForm.id = "";

  // 重置表单数据
  if (dataFormRef.value) {
    dataFormRef.value.resetFields();
  }

  if (id) {
    getInfo(id);
  }
};

const parseDomImg = (str: string) => {
  const htmlString: string = str;
  const parser = new DOMParser();
  const doc = parser.parseFromString(htmlString, "text/html");
  const imgElements: any = doc.querySelectorAll("img");
  const srcValues: any = [];
  imgElements.forEach((img: any) => {
    srcValues.push(img.src);
  });
  imgSrc.value = srcValues;
};

const uploadUrl = ref(`${app.api}/wechat/publicarticles/add_material?articleId=${dataForm.id}`);

// 获取信息
const getInfo = (id: number) => {
  baseService.get("/wechat/publicarticles/" + id).then((res) => {
    Object.assign(dataForm, res.data);
    uploadUrl.value = `${app.api}/wechat/publicarticles/add_material?articleId=${dataForm.id}&token=${getToken()}`;
    parseDomImg(res.data.content);
  });
};

const uploadBeforeUploadHandle = (file: any) => {
  console.log(dataForm);
  if (file.type !== "image/jpg" && file.type !== "image/jpeg" && file.type !== "image/png" && file.type !== "image/gif") {
    ElMessage.error(t("upload.tip", { format: "jpg、png、gif" }));
    return false;
  }
};
const uploadSuccessHandle = (res: any) => {
  if (res.code !== 0) {
    return ElMessage.error(res.msg);
  }
  visible.value = false;
  uploadRef.value.clearFiles();
};

// 表单提交
const dataFormSubmitHandle = () => {
  dataFormRef.value.validate((valid: boolean) => {
    if (!valid) {
      return false;
    }
    loading.value = true;
    baseService
      .put(`/wechat/publicarticles/add_material_url`, { articleId: dataForm.id, url: dataForm.url })
      .then((res) => {
        loading.value = false;
        ElMessage.success({
          message: t("prompt.success"),
          duration: 500,
          onClose: () => {
            visible.value = false;
            emit("refreshDataList");
          }
        });
      })
      .catch(() => {
        loading.value = false;
      });
  });
};

defineExpose({
  init
});
</script>

<style scoped>
.demo-image__preview {
  display: flex;
  flex-wrap: wrap;
}
.image-item {
  display: flex;
  flex-direction: column;
  width: 100px;
  justify-content: center;
  align-items: center;
  margin: 10px;
}
</style>
